package android.mobilin;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SettingsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
	Button save;
	Button back;
	EditText serverNumber;
	Builder builder;
	DBAdapter db;
	AlertDialog confirm;
	int id;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		save=(Button)findViewById(R.id.saveSett);
		back=(Button)findViewById(R.id.backSett);
		serverNumber=(EditText)findViewById(R.id.serverNumber);
		save.setOnClickListener(this);	
		back.setOnClickListener(this);
		db=new DBAdapter(this);
		builder = new Builder(this);
		builder.setCancelable(false)
		       .setPositiveButton("Yes", this)
		       .setNegativeButton("Cancel", this);
		String number="";
		Cursor num=db.query("setting");
		if(num!=null) {
    		int serverno=num.getColumnIndex("server_no");
    		int idno=num.getColumnIndex("_id");
    		if(num.moveToNext()) {
    			number=num.getString(serverno);
    			id=num.getInt(idno);
    			num.close();
    		}
    	}
    	serverNumber.setText(number);
	}

	public void onClick(View v) {
		if(v==save) {
			String phoneNo=serverNumber.getText().toString();
			if (phoneNo.length()==0) {
				Toast.makeText(this, "Please fill up the number field.", Toast.LENGTH_SHORT).show();
			}
			else {
				builder.setMessage("Change number to "+phoneNo+"?");
				confirm=builder.show();
			}
		}
		else if(v==back) {
			finish();
		}
	}

	public void onClick(DialogInterface dialog, int which) {
		if(dialog==confirm) {
			switch(which) {
				case DialogInterface.BUTTON_POSITIVE: 
					String phoneNo=serverNumber.getText().toString();
					db.remove("setting", id+"");
					db.insert("setting", phoneNo);
					Toast.makeText(this, "Number saved.", Toast.LENGTH_SHORT).show();
					break;
				case DialogInterface.BUTTON_NEGATIVE:
					confirm.dismiss();
					break;
			}
		}
	}
}
